import { BaseCommand, TSelectRanage } from '../types/common.interface';
import { TableDatas } from '../cors/table-datas';
import { Config } from '../cors/config';
import { RenderTrigger } from '../cors/render-trigger';

export class HiddenCellCommand extends BaseCommand {
    protected last: {[key: number]: number[]} = {};
    constructor(
        protected datas: TableDatas, 
        protected renderTrigger: RenderTrigger,
        protected conf: Config,
        protected range: TSelectRanage,
        protected isHidden: boolean
    ) {
        super();
    }
    protected saveLast() {
        this.conf.hiddenCells.forEach((cols, row) => {
            this.last[row] = Array.from(cols);
        });
    }
    public execute(): boolean {
        this.saveLast();
        for(let row = this.range.row; row < this.range.row + this.range.rowspan; row++) {
            for(let col = this.range.col; col < this.range.col + this.range.colspan; col++) {
                if(this.isHidden === true) {
                    if(this.conf.hiddenCells.has(row) === false) {
                        this.conf.hiddenCells.set(row, new Set());
                    }
                    let hiddenCols = this.conf.hiddenCells.get(col) as Set<number>;
                    hiddenCols.add(col);
                } else {
                    if(this.conf.hiddenCells.has(row) === true) {
                        let hiddenCols = this.conf.hiddenCells.get(col) as Set<number>;
                        hiddenCols.has(col) && hiddenCols.delete(col);
                        if(hiddenCols.size === 0) {
                            this.conf.hiddenCells.delete(row);
                        }
                    }
                }
            }
        }
        this.renderTrigger.triggerRenderAll();
        return true;
    }
    public redo(): boolean {
        this.conf.hiddenCells.clear();
        for(let row in this.last) {
            let cols = new Set(this.last[row]);
            this.conf.hiddenCells.set(Number(row), cols);
        }
        this.renderTrigger.triggerRenderAll();
        return true;
    }
}